import { defineStore } from 'pinia'
import { apiGetUserProfile } from '@/apis/auth'
import type { User } from '@/types'

interface UserStore {
  profile: User | null
}

const storeProfile = window.localStorage.getItem('profile')
export const userStore = defineStore('user', {
  state: (): UserStore => ({
    profile: storeProfile ? JSON.parse(storeProfile) : null
  }),

  actions: {
    /**
     * 获取当前登录用户信息
     */
    async queryUserProfile () {
      try {
        const data = await apiGetUserProfile<User>()
        this.profile = data
        window.localStorage.setItem('profile', JSON.stringify(data))
      } catch (error) {
        throw new Error()
      }
    },

    /**
     * 用户信息清除
     */
    clearProfile () {
      this.profile = null
      window.localStorage.removeItem('profile')
    }
  }
})
